﻿using System;
using System.Diagnostics;
using System.Drawing;
using System.Reflection;
using System.Windows.Forms;
using YonYou.U8.IN.Forms.StyleToolStrips;

namespace YonYou.U8.IN.Forms.StyleToolStrips
{
	public class ToolStripToolTipHelper
    {
		private ToolStrip owner;

		private MethodInfo methodSetTrackPosition = null;

		private MethodInfo methodSetTool = null;

		private MethodInfo methodStartTimer = null;

		private ToolStripItem lastActivetem = null;

		private ToolTip tooltip = null;

		public bool useCustomTooltip = true;

		public ToolStripToolTipHelper(ToolStrip toolStrip)
		{
			owner = toolStrip;
			owner.ShowItemToolTips = false;
		}

		public void ShowToolTip(MouseEventArgs mea)
		{
			if (useCustomTooltip)
			{
				ToolStripItem itemAt = owner.GetItemAt(mea.X, mea.Y);
				if (itemAt != null && itemAt != lastActivetem)
				{
					UpdateToolTip(itemAt);
				}
				lastActivetem = itemAt;
			}
		}

		public void clear()
		{
			owner = null;
		}

		public void HideToolTip()
		{
			if (tooltip != null)
			{
				try
				{
					tooltip.Hide(owner);
				}
				catch
				{
				}
			}
		}

		private void UpdateToolTip(ToolStripItem item)
		{
			if (tooltip == null)
			{
				PropertyInfo property = owner.GetType().GetProperty("ToolTip", BindingFlags.Instance | BindingFlags.NonPublic);
				tooltip = property.GetValue(owner, null) as ToolTip;
				Type type = tooltip.GetType();
				if (methodSetTrackPosition == null)
				{
					methodSetTrackPosition = type.GetMethod("SetTrackPosition", BindingFlags.Instance | BindingFlags.NonPublic);
				}
				if (methodSetTool == null)
				{
					methodSetTool = type.GetMethod("SetTool", BindingFlags.Instance | BindingFlags.NonPublic);
				}
				if (methodStartTimer == null)
				{
					methodStartTimer = type.GetMethod("StartTimer", BindingFlags.Instance | BindingFlags.NonPublic);
				}
			}
			if (tooltip != null)
			{
				try
				{
					tooltip.Hide(owner);
				}
				catch
				{
				}
				try
				{
					tooltip.Active = true;
					Point position = Cursor.Position;
					position.Y += owner.Cursor.Size.Height - owner.Cursor.HotSpot.Y;
					int x = position.X;
					int y = position.Y;
					methodSetTrackPosition.Invoke(tooltip, new object[2] { x, y });
					methodSetTool.Invoke(tooltip, new object[4] { owner, item.ToolTipText, 2, position });
					methodStartTimer.Invoke(tooltip, new object[2]
					{
					owner,
					tooltip.AutomaticDelay * 2
					});
				}
				catch (Exception ex)
				{
					Debug.WriteLine(ex.ToString());
				}
			}
		}
	}
}